package com.bs.resa.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author lin
 * @date 2019/3/8 13:24
 * 全局异常处理
 */
//
//@ResponseBody
//@ControllerAdvice
public class GlobalExceptionHandler{


    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception
    {
        System.out.println("异常："+e.getMessage());
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        Map<String,Object> map=new HashMap<>();
        map.put("code","500");
        map.put("message","error");
        JSON json=new JSONObject(map);
        writer.print(json);
        writer.flush();
        return null;
    }


    @ExceptionHandler(value = IOException.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e)
            throws Exception{
        return createModelAndView(request, "500", HttpStatus.INTERNAL_SERVER_ERROR, e);
    }

    private ModelAndView createModelAndView(HttpServletRequest request, String viewName, HttpStatus status, Exception e) {
        ModelAndView mav = new ModelAndView();
        if (e != null)
        {
            mav.addObject("error", e.getMessage());
        }
        mav.addObject("url", request.getRequestURI());
        mav.addObject("method", request.getMethod());
        if (status != null)
        {
            mav.setStatus(status);
        }
//        System.out.println("=============");
        mav.setViewName(viewName);
        return mav;
    }

}
